﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.Framework.Net;
using ZyGames.Framework.RPC.Sockets;
using ZyGames.Framework.Cache.Generic;
using System.Linq;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 房主点击开始游戏
	/// 游戏开发，TableData里面定时器启动计算房间时间
	/// </summary>
	public class Action30002 : BaseAction
	{
		private int _tableId;
		private TableData _currentTable;
		private bool _result = false;
		private string _log;
		

		public Action30002(HttpGet actionGetter)
			: base((short)ActionType.DZRequestStartGame, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableID", ref _tableId))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			try
			{
				_currentTable = GameRoom.Current.GetTableData(_tableId);
				if (_currentTable == null)
				{
					Tool.WriteErrorLine("消息30002获得房间不存在");
					return false;
				}
				var readyPosition = _currentTable.GetCurrentGetReadyPosition();
				if (readyPosition.Count < 2)
				{
					this._log = "当前桌子人数不足两人，不可以开局！";
					Tool.WriteErrorLine("消息30002当前桌子人数不足两人，不可以开局");
					return false;
				}
				_result = true;
				return true;
			}
			catch (Exception ex)
			{
				Tool.WriteErrorLine("30002消息异常:" + ex.ToString());
				return false;
			}
		}

		public override void TakeActionAffter(bool state)
		{
			if (_result)
			{
				_currentTable.TableReadyStart = true;
				var totalSecond = _currentTable.TimeLevelCost.TimeValue * 60;
				var time = totalSecond * 1000;   //180000
				//设置房间时间
				//var time = 30000;
				//开始房间倒计时
				_currentTable.StartTableTimer(time);

				//所有人开始时间倒计时
				var parameters = new Parameters();
				parameters["TableID"] = _tableId;
				parameters["Time"] = time;
				GameTable.Current.SyncNotifyAction((int)ActionType.DZBroadcastTimeLeft, _currentTable, parameters, t =>
				{
					Console.WriteLine("下发10050协议当前房间的剩余时间");
				});

				//检测开局
				GameTable.Current.CheckStart(_currentTable);
			}
			base.TakeActionAffter(state);
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this._result);
			this.PushIntoStack(this._log);
		}
	}
}
